<template>
  <keep-alive>
    <el-row class="customer-workbench-page">
      <el-row id="apassMicroCustomerWorkbench" class="page-container mp-micro" />
    </el-row>
  </keep-alive>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { loadMicroApp } from 'qiankun'
import { CommonModule } from '@/store/modules/common'
import { TemplateModule } from '@/store/modules/config/template'
import { mpCallMsgEvent } from '@/store/modules/cti/ctiEvent'
// import { getFormatDateTime } from '@/utils/common'
// import { SheetSummaryModule } from '@/store/modules/microAppStore/sheetSummary'
@Component({
  name: 'customerWorkbench'
})

export default class CustomerWorkbench extends Vue {
  // #region 基础数据
  private $route: any
  private $router: any
  private $bus: any
  private $message: any
  private microApp: any
  private currentRoute: string = ''
  private mpWorksheetDict = {}
  private $getCache: any
  private $store: any
  private mpData: any = {} // 小铃铛点击mp消息提醒跳转
  // #endregion

  // #region 子应用注册函数
  private initMicroApp (store) {
    const activeRule = '/crm_workBench/index'
    // mopower 打电话发短信的回调事件
    console.log(store, 'init传递======')
    this.$set(store, 'handleCallMessage', mpCallMsgEvent);
    this.$set(store, 'goTo', ({ applicationId, worksheetId, type, flowId }) => {
      if (['fields', 'workflow', 'editFlow'].includes(type)) {
        // 先获取 v7 这边存储的模板 id
        TemplateModule.TemplateCommonAction({
          url: '/crm/action/template/list',
          method: 'POST',
          data: {
            limit: 10,
            page: 1,
            status: 'enable',
            type: ['CUSTOMER']
          }
        }).then(res => {
          if (res && res.success) {
            if (res.list.length > 0) {
              // 根据不同的 type 做出不同的路由跳转
              switch (type) {
                case 'workflow': // 跳转至 模板配置-工作流列表
                case 'fields': // 跳转至 模板配置-字段设置
                  this.$router.push({
                    path: `/setting_center/index/customer_template_setting/edit/${res.list[0]._id}/${applicationId}/${worksheetId}/${type}`,
                    query: { routerTo: type }
                  })
                  break;
                case 'editFlow': // 跳转至 模板设置-工作流详情配置页
                  this.$router.push({
                    path: `/setting_center/index/customer_template_setting/edit/${res.list[0]._id}/${applicationId}/${worksheetId}/editFlow/${flowId}`,
                    query: { routerTo: `editFlow/${flowId}` }
                  })
                  break;
                default:
                  console.error('mopower goTo 函数未知 type:', type);
                  break;
              }
            }
          }
        })
      } else {
        console.error('mopower goTo 函数未知 type:', type);
      }
    })
    console.log(store, '======')
    this.microApp = loadMicroApp(
      {
        name: 'apass-micro-customerWorkbench',
        // entry: 'http://172.16.88.180:8080/sheetSummary.html', // 亚军本地
        entry: `${(CommonModule.initConfig as any).platformConfig.mopowerUrl}/sheetSummary.html`,
        container: '#apassMicroCustomerWorkbench',
        props: {
          headerHeight: -36, // 表头的高度
          callEvent: true, // 是否展示电话字段处的[打电话、发短信]功能
          routerBase: activeRule,
          store,
          user: {
            id: this.$store.state.common.mpInfo.mpUserId,
            companyId: this.$store.state.common.mpInfo.mpCompanyId
          }
        }
      },
      {
        sandbox: {
          // strictStyleIsolation: true
          // experimentalStyleIsolation: true
        }
      }
    )
  }

  private saveOrUpdateFun (res) { // 更新在线客户
    console.log(res)
    const data = JSON.parse(JSON.stringify(res))
    const dict = JSON.parse(JSON.stringify(this.mpWorksheetDict))
    for (const k in dict) {
      const v = dict[k]
      dict[v] = k
      delete dict[k]
    }
    for (const k in data) {
      if (dict[k]) {
        data[dict[k]] = data[k]
        delete data[k]
      }
    }
    console.log(dict)
    console.log(data)
    if (Object.keys(dict).length === 0) {
      console.error('/customer/config/cache接口返回的数据有问题')
    }
    const sendData = { customerId: data.id, customerName: data.name }
    const actionData = { url: '/im-center/action/customer/update', method: 'POST', data: sendData }
    CommonModule.publicAction(actionData)
  }

  private unmountMicroApp () {
    // console.log('this.microApp unmountMicroApp:\n', this.microApp)
    if (this.microApp) {
      this.microApp.mountPromise.then(() => {
        if (this.microApp.getStatus() === 'MOUNTED') {
          this.microApp.unmount()
        }
      })
    }
  }
  // #endregion

  // #region 生命周期钩子
  private initData () {
    CommonModule.getMpInfo({ url: '/auth/get/mp/relation', method: 'POST', data: {} }).then(() => {
      const data = {
        worksheetName: '客户列表', // （${getFormatDateTime(new Date(), '')}）
        applicationId: this.$store.state.common.mpInfo.mpApplicationId,
        worksheetId: this.$store.state.common.mpInfo.mpCrmWorksheetId,
        recordId: this.mpData.recordId || '',
        viewId: this.mpData.viewId || '',
        handleSaveFunc: (type, res) => {
          this.saveOrUpdateFun(res)
          console.log(res)
        }
      }
      this.$getCache('/crm/action/customer/config/cache', ['customerList'], false).then((cache: any) => {
        this.mpWorksheetDict = cache.customerList[0]
        this.initMicroApp(data)
      })
    })
  }

  public activated () {
    // console.log('customerIndex activated')
  }

  private deactivated () {
    // console.log('customerIndex deactivated')
    // this.unmountMicroApp()
    // this.$destroy()
  }

  private beforeRouteLeave (to: any, from: any, next: any) {
    // 注意：因为父子应用不是一个VueRouter实例，所以直接用$route取值取不到子应用push的路由，可参考下面congsole
    // 且：如果是在当前页面刷新，那么都能监听到；如果是从别的页面进来，两个值打印出来是不一样的
    // console.log('======= window: ', window.location.pathname)
    // console.log('======= from: ', from.fullPath)
    this.currentRoute = window.location.pathname
    this.mpData = {}
    next()
  }

  private beforeRouteEnter (to: any, from: any, next: any) {
    next((vm: any) => {
      const mpData = vm.$route.query.mpData
      if (mpData) { // 第一次进入，有带着记录id存起来，用于打开mp的记录详情
        vm.mpData = JSON.parse(mpData)
      }
      if (vm.currentRoute) {
        // 点击其他模块回到当前模块离开时的模块 || 刷新系统
        vm.$router.push({ path: vm.currentRoute })
      } else {
        vm.initData()
      }
    })
  }

  // #endregion
  private mounted () {
    this.$bus.$on('updateMpRecord', mpInfo => {
      if (this.microApp && mpInfo.type === 'CUSTOMER') { // 有挂载微应用 && 是客户模板的更新
        const data = {
          worksheetName: mpInfo.name,
          applicationId: mpInfo.data.applicationId,
          worksheetId: mpInfo.data.worksheetId,
          recordId: mpInfo.data.recordId, // 记录id
          viewId: mpInfo.data.viewId // 视图id
        }
        this.microApp.update({ type: 'changeWorksheet', data })
      }
    })
  }

  private beforeDestroy () {
    this.$bus.$off('updateMpRecord')
  }
}
</script>

<style lang="stylus" scoped>
  .customer-workbench-page
    width 100%
    height 100%
    border 1px solid $border-main
    box-shadow 0px 0px 4px 0px #E0E6F0, 0px 1px 4px 0px #E0E6F0
    border-radius 10px
    overflow auto
    background white url('../../assets/img/loading.gif') no-repeat center center
    background-size 1.2 1.2
</style>
